package tongwentongshu.com.app.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;

import butterknife.BindView;
import tongwentongshu.com.app.App;
import tongwentongshu.com.app.R;
import tongwentongshu.com.app.contract.MyReadingContract;
import tongwentongshu.com.app.db.Cache;
import tongwentongshu.com.app.fragment.BaseFragmentActivity;
import tongwentongshu.com.app.fragment.MyReadingFragment;
import tongwentongshu.com.app.utils.NetUtils;

/**
 * Created by XiongBin on 2017/7/12.
 */

public class MyReadingActivity extends BaseFragmentActivity implements MyReadingContract.View, View.OnClickListener,
        AdapterView.OnItemClickListener {
    /**
     * 导航栏
     */
    @BindView(R.id.hsv_view)
    HorizontalScrollView mHorizontalScrollView;
    /**
     * 导航条目
     */
    @BindView(R.id.hsv_content)
    LinearLayout mLinearLayout;
    /**
     * 导航底部线条
     */
    @BindView(R.id.iv_line)
    ImageView mImageView;
    /**
     * 页面展示ViewPager
     */
    @BindView(R.id.pager)
    ViewPager pager;
    /**
     * 导航条目宽度
     */
    private int item_width;
    /**
     * 主页加载的Fragment
     */
    private ArrayList<Fragment> fragments;
    /**
     * 导航栏动画相关参数
     */
    private int endPosition;
    private int beginPosition;
    private int currentFragmentIndex;
    private boolean isEnd;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_my_reading;
    }

    @Override
    protected int getTitleId() {
        return R.string.my_reading;
    }

    @Override
    protected void initView() {
        App.getApplication().addReadingActivity(this);
        item_width = (int) ((NetUtils.getDisplayMetrics(this, NetUtils.DM_WIDTH) / 6.0));
        mImageView.getLayoutParams().width = item_width;
        initViewPager();
        initNav();
    }

    @Override
    protected void initData() {

    }

    private void initViewPager() {
        fragments = new ArrayList<Fragment>();
        for (int i = 0; i < 6; i++) {
            Bundle data = new Bundle();
            data.putString(Cache.READING_KEY, String.valueOf(i));
            MyReadingFragment fragment = new MyReadingFragment(this);
            fragment.setArguments(data);
            fragments.add(fragment);
        }
        MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(
                getSupportFragmentManager(), fragments);
        pager.setAdapter(fragmentPagerAdapter);
        fragmentPagerAdapter.setFragments(fragments);
        pager.setOnPageChangeListener(new MyOnPageChangeListener());
        pager.setCurrentItem(0);
    }

    private void initNav() {
        String[] arrTag = {"全部", "预约书籍", "在读书籍", "空闲书籍", "被约书籍", "读过的书"};
        mLinearLayout.removeAllViews();
        for (int i = 0; i < arrTag.length; i++) {
            RelativeLayout layout = new RelativeLayout(this);
            TextView view = new TextView(this);
            int sizeOfText = (int) this.getResources().getDimension(R.dimen.h5);
            view.setTextSize(TypedValue.COMPLEX_UNIT_PX, sizeOfText);
            view.setText(arrTag[i]);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.CENTER_IN_PARENT);
            layout.addView(view, params);
            mLinearLayout.addView(layout, item_width, NetUtils.dip2px(mContext, 40));
            layout.setOnClickListener(this);
            layout.setTag(i);
        }
    }

    private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
        private ArrayList<Fragment> fragments;
        private FragmentManager fm;

        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
            this.fm = fm;
        }

        public MyFragmentPagerAdapter(FragmentManager fm,
                                      ArrayList<Fragment> fragments) {
            super(fm);
            this.fm = fm;
            this.fragments = fragments;
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        public void setFragments(ArrayList<Fragment> fragments) {
            if (this.fragments != null) {
                FragmentTransaction ft = fm.beginTransaction();
                for (Fragment f : this.fragments) {
                    ft.remove(f);
                }
                ft.commit();
                ft = null;
                fm.executePendingTransactions();
            }
            this.fragments = fragments;
            notifyDataSetChanged();
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            Object obj = super.instantiateItem(container, position);
            return obj;
        }

    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(final int position) {
            Animation animation = new TranslateAnimation(endPosition, position
                    * item_width, 0, 0);

            beginPosition = position * item_width;

            currentFragmentIndex = position;
            if (animation != null) {
                animation.setFillAfter(true);
                animation.setDuration(0);
                mImageView.startAnimation(animation);
                mHorizontalScrollView.smoothScrollTo((currentFragmentIndex - 1)
                        * item_width, 0);
            }
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {
            if (!isEnd) {
                if (currentFragmentIndex == position) {
                    endPosition = item_width * currentFragmentIndex
                            + (int) (item_width * positionOffset);
                }
                if (currentFragmentIndex == position + 1) {
                    endPosition = item_width * currentFragmentIndex
                            - (int) (item_width * (1 - positionOffset));
                }

                Animation mAnimation = new TranslateAnimation(beginPosition,
                        endPosition, 0, 0);
                mAnimation.setFillAfter(true);
                mAnimation.setDuration(0);
                mImageView.startAnimation(mAnimation);
                mHorizontalScrollView.invalidate();
                beginPosition = endPosition;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

            if (state == ViewPager.SCROLL_STATE_DRAGGING) {
                isEnd = false;
            } else if (state == ViewPager.SCROLL_STATE_SETTLING) {
                isEnd = true;
                beginPosition = currentFragmentIndex * item_width;
                if (pager.getCurrentItem() == currentFragmentIndex) {
                    // 未跳入下一个页面
                    mImageView.clearAnimation();
                    Animation animation = null;
                    // 恢复位置
                    animation = new TranslateAnimation(endPosition,
                            currentFragmentIndex * item_width, 0, 0);
                    animation.setFillAfter(true);
                    animation.setDuration(1);
                    mImageView.startAnimation(animation);
                    mHorizontalScrollView.invalidate();
                    endPosition = currentFragmentIndex * item_width;
                }
            }
        }

    }

    @Override
    public void onClick(View v) {
        pager.setCurrentItem((Integer) v.getTag());
    }


    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }
}
